package com.huhao.wshare.service.impl;

import com.huhao.wshare.dto.Friend.Request.*;
import com.huhao.wshare.dto.Friend.Response.AcceptFriendResponse;
import com.huhao.wshare.entity.Friends;
import com.huhao.wshare.entity.User;
import com.huhao.wshare.repository.FriendsRepository;
import com.huhao.wshare.repository.UserRepository;
import com.huhao.wshare.service.FriendService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional; // 引入 Optional 用于更优雅地处理 null
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FriendServiceImpl implements FriendService {

    private final UserRepository userRepository;
    private final FriendsRepository friendsRepository;
    private final Integer STATUS_PENDING = 0;
    private final Integer STATUS_ACCEPTED = 1;

    // ... getFriendList, getPendingFriendRequests 等其他方法保持不变 ...
    @Override
    @Transactional
    public FriendRequestInfo sendFriendRequest(Long currentUserId, AddFriendRequest request) {
        User currentUser = userRepository.findById(currentUserId)
                .orElseThrow(() -> new IllegalArgumentException("当前用户不存在"));
        User friendUser = userRepository.findById(request.getFriendId())
                .orElseThrow(() -> new IllegalArgumentException("目标用户不存在"));
        if (currentUser.getId().equals(friendUser.getId())) {
            throw new IllegalArgumentException("不能添加自己为好友");
        }
        if (friendsRepository.findByUserAndFriendAndStatus(currentUser, friendUser, STATUS_ACCEPTED).isPresent() ||
                friendsRepository.findByUserAndFriendAndStatus(friendUser, currentUser, STATUS_ACCEPTED).isPresent()) {
            throw new IllegalArgumentException("你们已经是好友了");
        }
        if (friendsRepository.findByUserAndFriendAndStatus(currentUser, friendUser, STATUS_PENDING).isPresent()) {
            throw new IllegalArgumentException("您已发送过好友请求，请勿重复发送");
        }
        if (friendsRepository.findByUserAndFriendAndStatus(friendUser, currentUser, STATUS_PENDING).isPresent()) {
            throw new IllegalArgumentException("对方已向您发送好友请求，请直接同意");
        }

        // --- 修改点：处理 remark 为 null 的情况 ---
        String remark = Optional.ofNullable(request.getRemark()).orElse("");

        Friends newRequest = new Friends();
        newRequest.setUser(currentUser);
        newRequest.setFriend(friendUser);
        // 使用处理过的 remark
        newRequest.setRemark(remark);
        newRequest.setStatus(STATUS_PENDING);
        friendsRepository.save(newRequest);
        return FriendRequestInfo.builder()
                .requesterName(currentUser.getUsername())
                .receiverName(friendUser.getUsername())
                // 返回处理过的 remark
                .remark(remark)
                .build();
    }

    @Override
    @Transactional
    public AcceptFriendResponse acceptFriendRequest(Long currentUserId, Long requestId, AcceptFriendRequest request) {
        Friends friendRequest = friendsRepository.findById(requestId)
                .orElseThrow(() -> new IllegalArgumentException("好友请求不存在"));

        if (!friendRequest.getFriend().getId().equals(currentUserId)) {
            throw new SecurityException("您无权操作此好友请求");
        }
        if (!friendRequest.getStatus().equals(STATUS_PENDING)) {
            throw new IllegalArgumentException("该请求已被处理，请勿重复操作");
        }

        // 更新原始请求的状态
        friendRequest.setStatus(STATUS_ACCEPTED);
        friendsRepository.save(friendRequest);

        // --- 修改点：处理 remark 为 null 的情况 ---
        String remark = Optional.ofNullable(request.getRemark()).orElse("");

        // 创建反向的好友关系
        Friends reverseFriendship = new Friends();
        reverseFriendship.setUser(friendRequest.getFriend());
        reverseFriendship.setFriend(friendRequest.getUser());
        // 使用处理过的 remark
        reverseFriendship.setRemark(remark);
        reverseFriendship.setStatus(STATUS_ACCEPTED);
        friendsRepository.save(reverseFriendship);

        // 准备成功信息
        String successMessage = String.format("您已成功添加 %s 为好友", friendRequest.getUser().getUsername());

        return new AcceptFriendResponse(successMessage);
    }

    @Override
    @Transactional
    public void rejectFriendRequest(Long currentUserId, Long requestId) {
        // 1. 查找好友请求
        Friends friendRequest = friendsRepository.findById(requestId)
                .orElseThrow(() -> new IllegalArgumentException("好友请求不存在"));

        // 2. 验证权限：只有请求的接收方可以拒绝
        if (!friendRequest.getFriend().getId().equals(currentUserId)) {
            throw new SecurityException("您无权操作此好友请求");
        }

        // 3. 验证请求状态
        if (!friendRequest.getStatus().equals(STATUS_PENDING)) {
            throw new IllegalArgumentException("该请求已被处理，无法拒绝");
        }

        // 4. 删除请求记录
        friendsRepository.delete(friendRequest);
    }


    /**
     * 【已修正】
     */
    @Override
    public List<FriendListItem> getFriendList(Long currentUserId) {
        User user = userRepository.findById(currentUserId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
        List<Friends> friendships = friendsRepository.findByUserAndStatus(user, STATUS_ACCEPTED);
        return friendships.stream()
                .map(friendship -> {
                    User friendUser = friendship.getFriend();
                    return FriendListItem.builder()
                            // 【新增】返回好友的用户ID
                            .friendId(friendUser.getId())
                            .account(friendUser.getAccount())
                            .username(friendUser.getUsername())
                            .signs(friendUser.getSigns())
                            .remark(friendship.getRemark()) // 这是我对好友的备注
                            .avatar(friendUser.getAvatar())
                            .gender(friendUser.getGender())
                            .build();
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<PendingFriendRequestItem> getPendingFriendRequests(Long currentUserId) {
        User user = userRepository.findById(currentUserId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
        List<PendingFriendRequestItem> pendingRequests = new ArrayList<>();
        List<Friends> sentRequests = friendsRepository.findByUserAndStatus(user, STATUS_PENDING);
        sentRequests.forEach(req -> {
            User receiver = req.getFriend();
            pendingRequests.add(PendingFriendRequestItem.builder()
                    .requestId(req.getId())
                    .account(receiver.getAccount())
                    .username(receiver.getUsername())
                    .avatar(receiver.getAvatar())
                    .gender(receiver.getGender())
                    .type("SENT")
                    .message("当前你添加 " + receiver.getUsername() + " 的好友请求还未被对方同意")
                    .build());
        });
        List<Friends> receivedRequests = friendsRepository.findByFriendAndStatus(user, STATUS_PENDING);
        receivedRequests.forEach(req -> {
            User sender = req.getUser();
            pendingRequests.add(PendingFriendRequestItem.builder()
                    .requestId(req.getId())
                    .account(sender.getAccount())
                    .username(sender.getUsername())
                    .avatar(sender.getAvatar())
                    .gender(sender.getGender())
                    .type("RECEIVED")
                    .message(sender.getUsername() + " 向你发送好友请求，请同意")
                    .build());
        });
        return pendingRequests;
    }

    @Override
    @Transactional
    public UpdateRemarkResponse updateFriendRemark(Long currentUserId, Long friendId, UpdateRemarkRequest request) {
        User currentUser = userRepository.findById(currentUserId)
                .orElseThrow(() -> new IllegalArgumentException("当前用户不存在"));
        User friendUser = userRepository.findById(friendId)
                .orElseThrow(() -> new IllegalArgumentException("目标好友不存在"));

        Friends friendship = friendsRepository.findByUserAndFriendAndStatus(currentUser, friendUser, STATUS_ACCEPTED)
                .orElseThrow(() -> new IllegalArgumentException("操作失败，对方不是您的好友或好友关系不存在"));

        // --- 修改点：处理 remark 为 null 的情况 ---
        String remark = Optional.ofNullable(request.getRemark()).orElse("");
        friendship.setRemark(remark);
        friendsRepository.save(friendship);

        return UpdateRemarkResponse.builder()
                .friendName(friendUser.getUsername())
                .remark(friendship.getRemark())
                .build();
    }
    /**
     * 删除好友的业务逻辑实现
     * @param currentUserId 当前用户 ID
     * @param friendId 要删除的好友的用户 ID
     */
    @Override
    @Transactional // 保证操作的原子性，要么都成功，要么都失败
    public void deleteFriend(Long currentUserId, Long friendId) {
        // 1. 查找用户实体
        User currentUser = userRepository.findById(currentUserId)
                .orElseThrow(() -> new IllegalArgumentException("当前用户不存在"));
        User friendToDelete = userRepository.findById(friendId)
                .orElseThrow(() -> new IllegalArgumentException("要删除的好友不存在"));

        // 2. 查找双向好友关系 (status=1 表示已是好友)
        // 关系1: 当前用户 -> 好友
        Friends friendship1 = friendsRepository.findByUserAndFriendAndStatus(currentUser, friendToDelete, 1)
                .orElse(null);
        // 关系2: 好友 -> 当前用户
        Friends friendship2 = friendsRepository.findByUserAndFriendAndStatus(friendToDelete, currentUser, 1)
                .orElse(null);

        // 3. 检查是否是好友关系
        if (friendship1 == null || friendship2 == null) {
            throw new IllegalStateException("你们还不是好友，无法删除");
        }

        // 4. 删除双向好友关系记录
        friendsRepository.delete(friendship1);
        friendsRepository.delete(friendship2);
    }
}
